package jp.co.neosystem.s2wg.util;

import java.io.PrintWriter;
import java.io.StringWriter;

public class Logger {

	public static void error(final Object msg) {
		log(LogType.ERROR, msg);
	}

	public static void warn(final Object msg) {
		log(LogType.WARN, msg);
	}

	public static void info(final Object msg) {
		log(LogType.INFO, msg);
	}

	public static void debug(final Object msg) {
		log(LogType.DEBUG, msg);
	}

	public static String getStackTrace(final Throwable t) {
		if (t == null) {
			return "";
		}

		final StringWriter sw = new StringWriter();
		final PrintWriter pw = new PrintWriter(sw);
		t.printStackTrace(pw);

		return sw.toString();
	}
	
	private static void log(final LogType type, final Object msg) {
		Logger.init();
		final String str = String.format("%s [%s:%d]", msg, getFileName(),
				getLineNumber());

		switch (type) {
		case ERROR:
			logger.error(str);
			break;
		case WARN:
			logger.warn(str);
			break;
		case INFO:
			logger.info(str);
			break;
		case DEBUG:
			logger.debug(str);
			break;
		default:
			break;
		}
	}

	private static int getLineNumber() {
		final Throwable t = new Throwable();
		return t.getStackTrace()[3].getLineNumber();
	}

	private static String getFileName() {
		final Throwable t = new Throwable();
		return t.getStackTrace()[3].getFileName();
	}

	private static void init() {
		if (logger == null) {
			logger = org.apache.log4j.Logger.getLogger("s2wg");
		}
	}

	private static org.apache.log4j.Logger logger;

	private static enum LogType {
		ERROR, WARN, INFO, DEBUG;
	}
}
